package com.fg.tliaswebmanagement.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

    /**
     * 过期时间
     */
    private static final int ACCESS_TOKEN_EXPIRE = 180 * 1000;

    /**
     * 加密算法
     */
    private static final SecureDigestAlgorithm<SecretKey, SecretKey> ALGORITHM = Jwts.SIG.HS256;

    /**
     * 私钥
     * 大于等于256位（长度32几以上的字符串）
     */
    private static final String SECRET = "fgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfg";

    /**
     * 密钥实例
     */
    public static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET.getBytes());

    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .header()
                .add("type","jwt")
                .add("alg","HS256")
                .and()
                .claims(claims)
                .expiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRE))
                .signWith(SECRET_KEY, ALGORITHM)
                .compact();
    }


    public static Claims parsePayload(String token){
        return Jwts.parser().verifyWith(SECRET_KEY).build().parseSignedClaims(token).getPayload();
    }
}
